package com.neighbor.neighborhooduser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.neighbor.neighborhooduser.dao.IPostsDao;
import com.neighbor.neighborhooduser.pojo.PostLikes;
import com.neighbor.neighborhooduser.dao.IPostLikesDao;
import com.neighbor.neighborhooduser.pojo.Posts;
import com.neighbor.neighborhooduser.pojo.Users;
import com.neighbor.neighborhooduser.service.IPostLikesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neighbor.neighborhooduser.utils.ReOpe;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 帖子点赞记录表 服务实现类
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:04
 */
@Service
public class PostLikesServiceImpl extends ServiceImpl<IPostLikesDao, PostLikes> implements IPostLikesService {
    @Autowired
    private ReOpe reOpe;
    @Autowired
    private IPostLikesDao postLikesDao;
    @Autowired
    private IPostsDao postsDao;


    @Override
    public Boolean setLike(Integer postId, HttpServletRequest request) {
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if (responseMsg.getCode() != ResponseMsg.SUCCESS) {

            return false;
        }
        Users user = (Users) responseMsg.getData();
        QueryWrapper<PostLikes> wrapper = new QueryWrapper<>();
        wrapper.eq("post_id",postId)
                        .eq("user_id",user.getUserId());
        boolean isLiked = postLikesDao.exists(wrapper);
        if(isLiked){
            postLikesDao.delete(wrapper);
            Posts post = postsDao.selectById(postId);
            post.setIsLiked(false);
            UpdateWrapper<Posts> PostsWrapper = new UpdateWrapper<>();
            PostsWrapper.set("like_count",post.getLikeCount()-1)
                            .eq("post_id",postId);
            postsDao.update(PostsWrapper);
            return false;
        }else{
            PostLikes postLikes = new PostLikes();
            postLikes.setPostId(postId);
            postLikes.setUserId(user.getUserId());
            postLikesDao.insert(postLikes);
            Posts post = postsDao.selectById(postId);
            post.setIsLiked(true);
            UpdateWrapper<Posts> PostsWrapper = new UpdateWrapper<>();
            PostsWrapper.set("like_count",post.getLikeCount()+1)
                    .eq("post_id",postId);
            postsDao.update(PostsWrapper);
            return true;
        }
    }
}
